var express = require('express');
var bodyParser = require('body-parser');
var sign = require('./sign.js');
var request = require('request');
var fs = require('fs');
var path = require('path');
var moment = require('moment');
exports.list = function(req,res){
	var data=sign.delEmptyValue(req.body);
	sign.dataReq(req,data,req.session.apikey,'/sysmanage/business/list','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})
}
exports.getProtocolList = function(req,res){
	sign.dataReq(req,req.body,req.session.apikey,'/sysmanage/business/getProtocolList','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})
}
exports.getBusiness = function(req,res){
	sign.dataReq(req,req.body,req.session.apikey,'/sysmanage/business/getBusiness','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})
}
exports.edit = function(req,res){
	sign.dataReq(req,req.body,req.session.apikey,'/sysmanage/business/edit','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})
}
exports.del= function(req,res){
	if(req.body.id){
		var data={'ids':[req.body.id]}
	}else if(req.body['id[]'].constructor == String){
		var data={'ids':[req.body['id[]']]}
	}else{
		var data={'ids':req.body['id[]']}
	}
	sign.dataReq(req,data,req.session.apikey,'/sysmanage/business/del','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})

}
exports.getAllProduct= function(req,res){
	sign.nullDataReq(req,req.session.apikey,'/sysmanage/product/getAllProduct','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})

}

exports.getAppList = function(req,res){
	sign.dataReq(req,req.body,req.session.apikey,'/sysmanage/business/getAppList','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})
} 
exports.exportData = function(req,res){
	request.get('http://192.168.2.140:8092/sysmanage/device/export?businessid='+req.body.businessid)
	.on('end', function() 
	  {
	  	var file = __dirname + '/../public/device.xls'; //__dirname返回本文件的所在的文件夹
	  	file  = path.resolve(file); //path.resolve返回device.xls的绝对路径
	  	//方案一
	    // res.download(file);
	    //方案二
	    var filestream = fs.createReadStream(file);
	    res.attachment('device-'+moment.unix(new Date() / 1000).format('YYYY-MM-DD')+'.xls');  //设置下载文件名称
	    res.set('Content-Type','application/octet-stream');//传输类型
	    filestream.pipe(res);
	  })
  	.pipe(fs.createWriteStream('public/device.xls'));//通过管道把写入文件流  
}
exports.importData = function(req,res){
	sign.importfileReq(req,req,req.session.apikey,'/sysmanage/device/upload','post',function(ResData){
		if(ResData!=''){
			res.send(ResData);
		}
	})
}